/**
 * 分组树状态管理
 */

const state = {
    // 当前选中的设备信息
    selectedDevice: null,
    // 当前选中的分组信息
    selectedGroup: null,
    // 分组树数据
    treeData: [],
    // 设备连接信息
    deviceConnection: {
        ipAddress: '',
        port: '8888',
        selectedSerialPort: '',
        baudRate: '9600'
    }
}

const getters = {
    // 获取当前选中的设备ID
    selectedDeviceId: state => {
        return state.selectedDevice ? state.selectedDevice.id : null
    },
    // 获取当前选中的分组ID
    selectedGroupId: state => {
        return state.selectedGroup ? state.selectedGroup.id : null
    },
    // 获取当前选中的设备信息
    selectedDeviceInfo: state => {
        return state.selectedDevice
    },
    // 获取当前选中的分组信息
    selectedGroupInfo: state => {
        return state.selectedGroup
    },
    // 获取设备连接信息
    deviceConnection: state => {
        return state.deviceConnection
    }
}

const actions = {
    // 设置选中的设备
    setSelectedDevice({ commit }, device) {
        commit('SET_SELECTED_DEVICE', device)
    },
    // 设置选中的分组
    setSelectedGroup({ commit }, group) {
        commit('SET_SELECTED_GROUP', group)
    },
    // 清除选中状态
    clearSelected({ commit }) {
        commit('CLEAR_SELECTED')
    },
    // 更新分组树数据
    updateTreeData({ commit }, treeData) {
        commit('UPDATE_TREE_DATA', treeData)
    },
    // 更新设备连接信息
    updateDeviceConnection({ commit }, connectionInfo) {
        commit('UPDATE_DEVICE_CONNECTION', connectionInfo)
    }
}

const mutations = {
    SET_SELECTED_DEVICE(state, device) {
        state.selectedDevice = device
    },
    SET_SELECTED_GROUP(state, group) {
        state.selectedGroup = group
    },
    CLEAR_SELECTED(state) {
        state.selectedDevice = null
        state.selectedGroup = null
    },
    UPDATE_TREE_DATA(state, treeData) {
        state.treeData = treeData
    },
    
    // 更新选中设备的状态
    updateSelectedDeviceStatus(state, isOnline) {
        if (state.selectedDevice) {
            state.selectedDevice = {
                ...state.selectedDevice,
                online: isOnline
            }
        }
    },
    
    // 更新设备连接信息
    UPDATE_DEVICE_CONNECTION(state, connectionInfo) {
        state.deviceConnection = {
            ...state.deviceConnection,
            ...connectionInfo
        }
    }
}

export default {
    namespaced: true,
    state,
    actions,
    getters,
    mutations
} 